<?php
declare (strict_types = 1);

namespace app\home\controller;



use app\BaseController;
use app\home\business\SendSms;
use app\home\model\User;
use app\home\validate\Register;
use app\Request;
use Mrwanghongda\SmsSdk\Sms\SmsFactory;
use think\App;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\View;
use Yurun\OAuthLogin\QQ\OAuth2;


class Index extends Base
{
    const SMS_TENCENT = 'tencent';
    public $qqAuth=null;
    public function __construct(App $app)
    {
        parent::__construct($app);
        //实例化第三方登录

        $this->qqAuth=new OAuth2('101542020', '539cd4f7784f107fa74ad58d87b5c916', 'http://www.tpshop.com/index.php/home/login/qqcallback');

    }

    public function qqLogin(){
        $url = $this->qqAuth->getAuthUrl();
        header('location:' . $url);
    }

    //  首页
    public function index()
    {
        return view();
    }

    // 登录页面
    public function login(){
        View::config(['layout_on' => false]);
        return view('login');

    }

    // 注册页面
    public function register(){
        View::config(['layout_on' => false]);
        return view('register');
    }

    // 发送短信验证码
    public function sendSms(Request $request){
        $data=$request->post();
        $phone=$request->post('phone');
        // 生成随机验证码
        $code=rand(00000,9999);
        if (Cache::get("$phone"."_time")){
            return fail('发送次数频繁');
        }
//        $res=SendSms::sendInfo($code,$phone);
        // 将验证码放入缓存
        Cache::set("$phone"."_code","$code",300);
        // 缓存验证码发送时间
        Cache::set("$phone"."_time",time(),60);
        return success($code);
    }
    // 完成注册
    public function finish(){
        $data=\request()->post();
        $code=$data['code'];
        $phone=$data['phone'];
        $password=$data['pwd'];
        // 取出手机号对应的验证码缓存
        $num=Cache::get("$phone"."_code");
        // 判断验证码是否存在
        if (empty($num)){
            return json([
                'code'=>100,
                'msg'=>'验证码过期'
            ]);
        }
        // 判断验证码是否正确
        if ($code !=$num){
            return json([
                'code'=>100,
                'msg'=>'验证码不正确'
            ]);
        }
        // 将手机号加密
        $nickname=substr_replace($phone,'****',3,4);
        $data=[
            'nickname'=>$nickname,
            'username'=>$phone,
            'phone'=>$phone,
            'password'=>pwd($password)
        ];
        // 注册数据入库
        $res=User::addUser($data);
        if ($res){
            return json([
                'code'=>200,
                'msg'=>'注册成功'
            ]);
        }

    }
    public function qqcallback(){

    }

}
